# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
from ui import Ui_main_windows
import sys

class main_windows(QtGui.QMainWindow):
    def __init__(self,parent=None):
        #界面显示
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_main_windows()
        self.ui.setupUi(self)
        self.ui.textEdit.setText(u'界面初始化完成') 
        #变量初始化
        self.filename=""
        self.url_login_page=r'http://acm.hdu.edu.cn/userloginex.php?action=login'
        self.url_submit_page=r'http://acm.hdu.edu.cn/submit.php?action=submit'
        #绑定函数        
        QtCore.QObject.connect(self.ui.pushButton_test_login, \
        QtCore.SIGNAL("clicked()"),self.test_login)
        QtCore.QObject.connect(self.ui.pushButton_choose_code, \
        QtCore.SIGNAL("clicked()"),self.choose_code)
        QtCore.QObject.connect(self.ui.pushButton_submit, \
        QtCore.SIGNAL("clicked()"),self.submit)
        self.print_log(u'请输入用户名和密码并点击测试登录按钮')
        self.test()    
    def choose_code(self):  
        file_dialog=QtGui.QFileDialog()
        self.filename = file_dialog.getOpenFileName()
        from os.path import isfile
        if isfile(self.filename):
            self.print_log(u'打开文件成功')    
            self.ui.label_code_path.setText(self.filename)
            if self.filename[-4:]!='.cpp' and self.filename[-2:]!='.c' :
                self.print_log(u'文件似乎不是源代码文件,确定?')  
            return True
        else :
            self.print_log(u'打开文件失败')
            return False
            
        
    def test(self):
        print 'test start'
        self.ui.lineEdit_username.setText('hnust_wangkechun')
        self.ui.lineEdit_password.setText('')
        self.ui.label_code_path.setText(r'E:/python/ojsubmmiter/ojsubmmiter/main.cpp')
        self.filename=r'E:/python/ojsubmmiter/ojsubmmiter/main.cpp'
        print 'test end'
    def print_log(self,s):
        old=self.ui.textEdit.toPlainText()
        self.ui.textEdit.setPlainText(old+'\n'+s)
    def test_login(self):
        import urllib2,urllib,cookielib
        print 'test_login'
        self.username = self.ui.lineEdit_username.text()
        self.password = self.ui.lineEdit_password.text() 
        if len(self.username)==0 :
            self.print_log(u'请输入用户名')
            return False
        if len(self.password)==0 :
            self.print_log(u'请输入密码')
            return False
        self.print_log(u'登录中')
        cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
        self.opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
        postdata=urllib.urlencode({
            'username':self.username,
            'userpass':self.password,
            'login':'Sign In'
        })
        try:        
            content=self.opener.open(self.url_login_page,postdata).read()
        except:
            self.print_log(u'登录遇到未知错误')
            return False
        if content.find(r'No such user or wrong password.')!=-1 : 
            self.print_log(u'登录失败,请检查你的用户名和密码')            
            return False
        if content.find(self.username) :
            self.print_log(u'恭喜你,登录成功')            
            return True
    def submit(self):
        self.print_log(u'*****************')
        self.print_log(u'正在准备提交')
        if len(self.filename)==0 :
            self.print_log(u'没有选择源代码文件')
            return False
        if self.test_login()==False :
            self.print_log(u'登录失败')
            return False
        from os.path import isfile
        if isfile(self.filename)==False:
            self.print_log(u'打开文件失败')
            return False
        try:
            self.content=open(self.filename).read()
        except:
            self.print_log(u'打开文件遇到未知错误')
            return False
        self.print_log(u'打开文件成功')
        self.re_file()
        self.print_log(u'判题结束')
        
        
        
    def re_file(self):
        import re,urllib
        try:
            qid=re.match('.*//hdu (\d\d\d\d)',self.content,re.S).group(1)
        except:
            self.print_log(u'没有检测到题号信息,请在代码中加入//hdu 1234之类的注释表明题号')
            return False
        self.print_log(u'正在提交%s题...'%qid)
        postdata=urllib.urlencode({
            'check':'0',
            'problemid':qid,
            'language':0, #G++
            'usercode':self.content
        })
        #try:        
        self.content=self.opener.open(self.url_submit_page,postdata).read()
        #except:
        #    self.print_log(u'网络故障')
        #    return False
        self.print_log(u'代码已经提交成功,正在获取判题状态')
        url_get_status=u'http://acm.hdu.edu.cn/status.php?first=&pid=%s&user=%s&lang=%s&status=%s'% \
            (qid,self.username,'0','0')
        #print url_get_status
        import time
        rep=r'''(\d{7})
            <.*?font.*?>(.+?)<\/font
            .*?>.*?>.*?>.*?>
            (\d{4})
            .*?>.*?>.*?>
            (.+?)
            <.*?>.*?>
            (.+?)
            <.*?>.*?>.*?>
            (.+?)
            <.*?>.*?>
            (.+?)
            <.*?>.*?>.*?>'''
        while_i=0
        while while_i<10:
            time.sleep(2)
            html=self.opener.open(url_get_status).read().replace('\n','')
            #print html
            relist=re.findall(rep,html,re.X)
            self.print_log(str(relist[0]))
            if relist[0][1]!='Queuing':
                return True
            while_i=while_i+1
            #return 
            
        

if __name__ == "__main__":
    print 'main'
    app=QtGui.QApplication(sys.argv)
    myapp=main_windows()
    myapp.show()
    sys.exit(app.exec_())
    